package com.neusoft.chenanqi.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import com.neusoft.chenanqi.dto.EmpSalDto;

public class ImportExcelUtil {

	public static List<EmpSalDto> importEmpSal(InputStream inputStream)
			throws BiffException, IOException, NumberFormatException, 
			ArrayIndexOutOfBoundsException {
		
		List<EmpSalDto> empSalDtoList = new ArrayList<EmpSalDto>();

		// 创建工作簿
		Workbook workbook = Workbook.getWorkbook(inputStream);

		// 获取工作表
		Sheet[] sheets = workbook.getSheets();
		for (int i = 0; i < sheets.length; i++) {
			Cell[] tableHeadCells = sheets[i].getRow(0);
			if (tableHeadCells.length > 0) {
				List<String> salItemName = new ArrayList<String>();
				for (int j = 2; j < tableHeadCells.length; j++) {
					salItemName.add(tableHeadCells[j].getContents());
				}
				int tableRowNum = sheets[i].getRows();
				for (int j = 1; j < tableRowNum; j++) {
					Cell[] rowCells = sheets[i].getRow(j);
					EmpSalDto empSalDto = new EmpSalDto();
					Integer empNo = Integer.parseInt(rowCells[0].getContents());
					empSalDto.setEmpNo(empNo);
					empSalDto.setEmpName(rowCells[1].getContents());
					empSalDto.setSalItemName(salItemName);
					List<String> salItemValue = new ArrayList<String>();
					for (int k = 0; k < salItemName.size(); k++) {
						String value = rowCells[k + 2].getContents();
						if (value != null && !"".equals(value)) {
							if (Double.parseDouble(rowCells[k + 2].getContents()) >= 0) {
								salItemValue.add(value);
							} else {
								throw new NumberFormatException();
							}
						} else {
							salItemValue.add("*");
						}
						
					}
					empSalDto.setSalItemValue(salItemValue);
					empSalDtoList.add(empSalDto);
				}
			}
		}
		return empSalDtoList;
	}
}
